(function($) {

//var plugin = {
//	//Nom de la classe à instancier /!\ CE NOM DOIT ETRE UNIQUE ET IDENTIQUE AU NOM JQUERY /!\
//	name: 'OrderPlugin'
//};

// Constructeur
var OrderPlugin = function(options){ // rajouter element
	//console.log(this);
	if(arguments.length) {
		this._init( options );// rajouter element
	} else 
		console.log('Aucun paramètre reçu pour OrderPlugin');
};

OrderPlugin.prototype = {
	name: 'OrderPlugin',
	
	defaults: {
		data: {
		}
	},
	
	defaultOrder: {
		id: 0,
		content: '',
		state: 1,
		isNew: 1,
		isDelete: 0,
		position: 0
	},
	
	_init: function(options){// rajouter element
		var t = this;
		
		// Public
		t.$element = $(options.element);
		t.defaults = $.extend(true, {}, t.defaults, options);
		
		t.idEvent = t.defaults.idEvent;
		t.isLock = false;
		
		t.orders = {};
				
		if(t.idEvent == 0){
			t.$element.html('<div class="alert">L\'événement doit être enregistré pour saisir l\'ordre du jour');
		} else {
			t.$element.html(t.defaults.content);
			
			var sorting = [];
			
			$('#em-plugin-order-list li').each(function(){
				var count = $(this).data('count'),
					order = $.extend(true, {}, t.defaultOrder, {
					id:$(this).data('id'),
					content: $(this).find('.em-plugin-order-content').text(),
					state: ($(this).find('input[type=checkbox]').is(':checked')) ? 1:0,
					isNew: 0,
					position : count
				});
					
				$(this).remove();
				t.orders[count] = order;
				
				sorting.push(count);
			});
			
			sorting = sorting.sort();
			
			for(var i = sorting.length-1; i>=0; i--){
				t.render(sorting[i], t.orders[sorting[i]]);
			}
			
			$('#em-plugin-order-list').sortable({
				placeholder: 'placeholder', 
				forcePlaceholderSize: true, 
				update: function(event, ui) {
					$(ui.item).parents('#em-plugin-order-list').children('li').each(function(i, li) {
						t.orders[$(this).data('count')].position = i;
					});
					
					t.submitOrders();
				}
			});
			
			$('#em-plugin-order-form').on('submit', function(e){
				e.preventDefault();
				
				var $input = $(this).find('input[type=text]'),
					count = $('#em-plugin-order-list li').size();
				
				if($input.val() && !t.isLocked()){
					count++;
					
					var order = $.extend(true, {}, t.defaultOrder, {
						id:0,
						content: $input.val(),
						state: 0,
						isNew: 1,
						position : count
					});
					
					t.render(count, order);
						
					t.orders[count] = order;
					
					t.submitOrders();
					
				}
			});
		}
	},
	
	render: function(count, order){
		var t = this,
			$liOrder = $(''+
			'<li data-id="0" data-count="'+count+'">'+
                '<label class="checkbox"><input type="checkbox" class="uniform"></label>'+
                '<span class="text">'+
                    '<span class="text-nowrap em-plugin-order-content">'+order.content+'</span>'+
                '</span>'+
                '<a href="#" class="close">&times;</a>'+
            '</li>'
		).prependTo($('#em-plugin-order-list'));
		
		if(order.state){
			$liOrder.find('input[type=checkbox]').attr('checked', true);
			$liOrder.addClass('done');
		}		

		$liOrder.data('count', count);
		$liOrder.data('id', order.id);
		
		t.attachEvents($liOrder);
	},
	
	attachEvents: function($element){
		var t = this;
		
		$element.find('input[type=checkbox]').on('click', function(e){
			if(!t.isLocked()){
				if($(this).is(':checked')){
					$element.addClass('done');
					t.orders[$element.data('count')].state = 1;
				} else {
					$element.removeClass('done');
					t.orders[$element.data('count')].state = 0;
				}
				 
				t.submitOrders();
			} else {
				e.preventDefault();
			}
		});
		
		$element.find('a.close').on('click', function(e){
			e.preventDefault();
			
			if(!t.isLocked()){
				t.orders[$element.data('count')].isDelete = 1;
				
				$element.remove();
				
				t.submitOrders();
			}
		});
	},
	
	isLocked: function(){
		var t = this;
		
		if(t.isLock){
			$.pnotify({
                title: "Action impossible",
                text: 'Un échange est en cours ...',
                type: "alert"
            });
			
			return true;
		}
		
		return false;
	},
	
	submitOrders : function(callback){
		var t = this,
			dataSend = {orders: t.orders};
				
		if(t.idEvent == 0){
			$.pnotify({
                title: "Erreur !",
                text: 'L\'événement doit être créer pour enregistrer l\'ordre du jour',
                type: "error"
            });
			return;
		}
		
		t.isLock = true;
		
		var urlUpdate = t.defaults.options.urlBase + 
			t.defaults.options.urlPattern
				.replace(/idEvent/, t.idEvent)
				.replace(/action/, t.defaults.options.urlUpdateAction);
		
		$.ajax({
    		type: 'POST',
    		url: urlUpdate,
		  	data: dataSend,
		    dataType: "json"
    	}).done(function(jsonResult) {
    		if(jsonResult && typeof jsonResult.result != 'undefined'){
        		if(jsonResult.result == 200){
        			$.each(jsonResult.orders, function(k, v){
        				t.orders[v.count].id = v.id;
        				t.orders[v.count].isNew = 0;
        			})
        			        			
        			if(typeof callback == 'function'){
        				callback();
        			} else {
        				$.pnotify({
	                        title: "Terminé !",
	                        text: jsonResult.msg,
	                        type: "success"
	                    });
        			}
        		} else if(jsonResult.result == 500){
        			$.pnotify({
                        title: "Erreur !",
                        text: jsonResult.msg,
                        type: "error"
                    });
        		}
    		} else {
    			alert('La réponse du serveur est incorrecte');
        	}
    	}).fail(function(jqXHR, textStatus, errorThrown) {
    		t.refresh();
    		alert('Une erreur est survenue ('+errorThrown+')');
    	}).always(function(jqXHR, textStatus, errorThrown) {
    		t.isLock = false;
    	});
	},
	
};

$.fn.pluginParticipantsEvent = function(options) {

	var isMethodCall = typeof options === "string",
		args = Array.prototype.slice.call( arguments, 1 ),
		returnValue = this;

	// prevent calls to internal methods
	if ( isMethodCall && options.charAt( 0 ) === "_" ) {
		return returnValue;
	}

	if ( isMethodCall ) {
		this.each(function() {
			var instance = $.data( this, 'OrderPlugin' ),
				methodValue = instance && $.isFunction( instance[options] ) ?
					instance[ options ].apply( instance, args ) :
					instance;

			if ( methodValue !== instance && methodValue !== undefined ) {
				returnValue = methodValue;
				return false;
			}
		});
	} else {
		this.each(function() {
			var instance = $.data( this, 'OrderPlugin' );
			if ( !instance ) {
				$.data( this, 'OrderPlugin', new OrderPlugin( this, options ) );
			}
		});
	}

	return returnValue;
};

// Association en tant que plugin jQuery
//$.fn.OrderPlugin = plugin.OrderPlugin;

// Si l'eventManager a été déclaré on le surcharge pour la gestion du plugin
if(typeof $.eventManager != 'undefined'){
	var em = $.eventManager;
	
	// Ajout du plugin au register du manager, il sera instancié par le manager automatiquement
	em.addPluginToRegister('OrderPlugin', OrderPlugin);
	
	// Ajout d'une fonction lors du callback du init plugins
	em.addCallBackInit(function(){
	});
}

})(jQuery);